package com.example.demo.response;

import com.example.demo.constant.CommonConstants;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Optional;
import java.util.function.Function;

/**
 * 响应信息主体
 *
 * @param <T>
 * @author YB
 */
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
//@ApiModel(value = "响应信息主体")
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    public static final String SUCCESS_MSG = "操作成功";

    @Getter
    @Setter
//	@ApiModelProperty(value = "返回标记：成功标记=0，失败标记=1")
    private int code;

    @Getter
    @Setter
//	@ApiModelProperty(value = "返回信息")
    private String msg;

    @Getter
    @Setter
//	@ApiModelProperty(value = "数据")
    private T data;

    public static <T> R<T> ok() {
        return restResult(null, CommonConstants.SUCCESS, null);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, CommonConstants.SUCCESS, null);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, CommonConstants.SUCCESS, msg);
    }

    public static <T> R<T> failed() {
        return restResult(null, CommonConstants.FAIL, null);
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, CommonConstants.FAIL, msg);
    }

    public static <T> R<T> failed(Integer code, String msg) {
        if(code == null){
            code = CommonConstants.FAIL;
        }
        return restResult(null, code, msg);
    }

    public static <T> R<T> failed(T data) {
        return restResult(data, CommonConstants.FAIL, null);
    }

    public static <T> R<T> failed(T data, String msg) {
        return restResult(data, CommonConstants.FAIL, msg);
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public static <T> R<T> notNull(T data, String msg) {
        return restResult(data, (data == null ? CommonConstants.FAIL : CommonConstants.SUCCESS), msg);
    }

    public static <T> R<T> notNull(T data) {
        return notNull(data, null);
    }

    public <S> R<S> map(Function<R<T>, R<S>> func) {
        return func.apply(this);
    }

    public <S> R<S> mapData(Function<Optional<T>, S> func) {
        return restResult(func.apply(Optional.ofNullable(this.data)), this.code, this.msg);
    }

    public boolean codeEq(int code) {
        return this.code == code;
    }

    public boolean success() {
        return codeEq(CommonConstants.SUCCESS);
    }

}
